<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 5.4.2">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"xiaoqingming18.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.15.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="输入输出流介绍输入流输入流分为字节输入流InputStream和字符输入流Reader，它们都是抽象类。下图给出了InputStream类和Reader类的层次结构。 输出流输出流分为字节输出流OutputStream和字符输出流Writer，它们也都是抽象类。下图给出了OutputStream类和Writer类的层次结构。 输入流InputStream类下面是InputStream类的一些常用方">
<meta property="og:type" content="article">
<meta property="og:title" content="Java：输入输出流">
<meta property="og:url" content="http://xiaoqingming18.github.io/2023/05/24/Java%EF%BC%9A%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81/index.html">
<meta property="og:site_name" content="鸣蜩十七">
<meta property="og:description" content="输入输出流介绍输入流输入流分为字节输入流InputStream和字符输入流Reader，它们都是抽象类。下图给出了InputStream类和Reader类的层次结构。 输出流输出流分为字节输出流OutputStream和字符输出流Writer，它们也都是抽象类。下图给出了OutputStream类和Writer类的层次结构。 输入流InputStream类下面是InputStream类的一些常用方">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-05-24T14:24:23.000Z">
<meta property="article:modified_time" content="2023-05-24T16:18:39.152Z">
<meta property="article:author" content="鸣蜩十七">
<meta property="article:tag" content="-Java基础 -输入输出流">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://xiaoqingming18.github.io/2023/05/24/Java%EF%BC%9A%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://xiaoqingming18.github.io/2023/05/24/Java%EF%BC%9A%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81/","path":"2023/05/24/Java：输入输出流/","title":"Java：输入输出流"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java：输入输出流 | 鸣蜩十七</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">鸣蜩十七</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">鸣蜩十七是和女朋友谈恋爱的日子</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-schedule"><a href="/schedule/" rel="section"><i class="fa fa-calendar fa-fw"></i>日程表</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-commonweal"><a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
  </ul>
</nav>




</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81%E4%BB%8B%E7%BB%8D"><span class="nav-text">输入输出流介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BE%93%E5%85%A5%E6%B5%81"><span class="nav-text">输入流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BE%93%E5%87%BA%E6%B5%81"><span class="nav-text">输出流</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BE%93%E5%85%A5%E6%B5%81-1"><span class="nav-text">输入流</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#InputStream%E7%B1%BB"><span class="nav-text">InputStream类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Reader%E7%B1%BB"><span class="nav-text">Reader类</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">鸣蜩十七</p>
  <div class="site-description" itemprop="description">记录我的学习、生活和恋爱日常</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xiaoqingming18.github.io/2023/05/24/Java%EF%BC%9A%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="鸣蜩十七">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="鸣蜩十七">
      <meta itemprop="description" content="记录我的学习、生活和恋爱日常">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java：输入输出流 | 鸣蜩十七">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java：输入输出流
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-05-24 22:24:23" itemprop="dateCreated datePublished" datetime="2023-05-24T22:24:23+08:00">2023-05-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-25 00:18:39" itemprop="dateModified" datetime="2023-05-25T00:18:39+08:00">2023-05-25</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">-后端</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="输入输出流介绍"><a href="#输入输出流介绍" class="headerlink" title="输入输出流介绍"></a>输入输出流介绍</h1><h2 id="输入流"><a href="#输入流" class="headerlink" title="输入流"></a>输入流</h2><p>输入流分为<strong>字节输入流</strong><code>InputStream</code>和<strong>字符输入流</strong><code>Reader</code>，它们都是抽象类。下图给出了<code>InputStream</code>类和<code>Reader</code>类的层次结构。</p>
<h2 id="输出流"><a href="#输出流" class="headerlink" title="输出流"></a>输出流</h2><p>输出流分为<strong>字节输出流</strong><code>OutputStream</code>和<strong>字符输出流</strong><code>Writer</code>，它们也都是抽象类。下图给出了<code>OutputStream</code>类和<code>Writer</code>类的层次结构。</p>
<h1 id="输入流-1"><a href="#输入流-1" class="headerlink" title="输入流"></a>输入流</h1><h2 id="InputStream类"><a href="#InputStream类" class="headerlink" title="InputStream类"></a>InputStream类</h2><p>下面是<code>InputStream</code>类的一些常用方法和说明：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>abstract int read()</td>
<td>从数据中读入一个字节，返回一个字节的数据（0-255的整数值），如果已经读取到流的末尾，返回 -1 表示没有更多的数据可读取。</td>
</tr>
<tr>
<td>int read(byte[] b)</td>
<td>返回实际读取的字节数，将读取的数据存储到给定的字节数组 <code>b</code> 中，读取的实际字节数为<code>b.length</code>。</td>
</tr>
<tr>
<td>int read(byte[] b,int off,int len)</td>
<td>返回实际读取的字节数，将读取的数据存储到给定的字节数组 <code>b</code> 的指定偏移量 <code>off</code> 开始的位置，并最多读取 <code>len</code> 个字节的数据。</td>
</tr>
<tr>
<td>byte[] readAllBytes()</td>
<td>返回一个数组，包含可以从当前流中读入的所有字节</td>
</tr>
<tr>
<td>long transferTo(OutputStream)</td>
<td>将当前输入流中的所有字节传送到给定的输出流，返回传递的字节数。<strong>这两个流都不能处于关闭状态</strong>。</td>
</tr>
<tr>
<td>long skip(long n)</td>
<td>在输入流中跳过n个字节，返回实际跳过的字节数（如果碰到数据流结尾，可能小于0）。</td>
</tr>
<tr>
<td>int available()</td>
<td>返回在不阻塞情况下可以读取的字节数。</td>
</tr>
<tr>
<td>void close()</td>
<td>关闭这个输入流。</td>
</tr>
<tr>
<td>void mark(int readLimit)</td>
<td>在输入流的当前位置打一个标记（并非所有的流都支持此特性），如果从输入流中已经读取的字节数多于<code>readLimit</code>个，则这个流允许忽略这个标记。</td>
</tr>
<tr>
<td>void reset()</td>
<td>返回到最后一个标记，随后对read的调用将重新读入这些字节。如果当前流没有任何标记，则这个流不被重置。</td>
</tr>
<tr>
<td>boolean markSupported()</td>
<td>如果这个流支持打标记，则返回<code>true</code>。</td>
</tr>
</tbody>
</table>
</div>
<p>要注意的是，<code>read()</code> 方法是一个抽象方法。抽象方法是在抽象类中声明但没有具体实现的方法，因此无法直接实例化抽象类。但可以使用 <code>InputStream</code> 类的具体子类来创建对象，并使用子类中实现的 <code>read()</code> 方法。这些子类是具体的输入流实现，例如 <code>FileInputStream</code>、<code>ByteArrayInputStream</code> 等。这些具体子类继承自 <code>InputStream</code> 并提供了对输入源的具体读取操作。</p>
<p>另外，上述最后 3 个方法一般会结合在一起使用完成<strong>重复读取操作</strong>，首先使用 markSupported() 判断当前流是否支持标记，如果可以，则使用 mark(int readLimit) 方法进行标记，标记完成之后可以使用 read() 方法读取标记范围内的字节数，最后使用 reset() 方法使输入流重新定位到标记的位置，继而完成重复读取操作。看下面的例子：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.FileInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RepeatReadExample</span> {</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> {</span><br><span class="line">        <span class="keyword">try</span> {</span><br><span class="line">            <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">"file.txt"</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 设置标记，读取的字节数限制为10</span></span><br><span class="line">            inputStream.mark(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 第一次读取</span></span><br><span class="line">            System.out.println(<span class="string">"First read:"</span>);</span><br><span class="line">            readData(inputStream, <span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 重置输入流，返回到标记位置</span></span><br><span class="line">            inputStream.reset();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 第二次读取</span></span><br><span class="line">            System.out.println(<span class="string">"Second read:"</span>);</span><br><span class="line">            readData(inputStream, <span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">            inputStream.close();</span><br><span class="line">        } <span class="keyword">catch</span> (IOException e) {</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">readData</span><span class="params">(InputStream inputStream, <span class="type">int</span> numBytes)</span> <span class="keyword">throws</span> IOException {</span><br><span class="line">        <span class="type">byte</span>[] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[numBytes];</span><br><span class="line">        <span class="type">int</span> <span class="variable">bytesRead</span> <span class="operator">=</span> inputStream.read(buffer);</span><br><span class="line">        <span class="keyword">if</span> (bytesRead != -<span class="number">1</span>) {</span><br><span class="line">            System.out.println(<span class="string">"Read: "</span> + <span class="keyword">new</span> <span class="title class_">String</span>(buffer, <span class="number">0</span>, bytesRead));</span><br><span class="line">        } <span class="keyword">else</span> {</span><br><span class="line">            System.out.println(<span class="string">"End of stream reached."</span>);</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"></span><br></pre></td></tr></tbody></table></figure>
<h3 id="Reader类"><a href="#Reader类" class="headerlink" title="Reader类"></a>Reader类</h3><figure class="highlight plaintext"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">AnalysisResult</span><br></pre></td></tr></tbody></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java%E5%9F%BA%E7%A1%80-%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%B5%81/" rel="tag"># -Java基础 -输入输出流</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/05/21/Java%EF%BC%9AIO%E6%B5%81/" rel="prev" title="Java：IO流">
                  <i class="fa fa-chevron-left"></i> Java：IO流
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/05/31/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%8E%9F%E7%90%86%EF%BC%9A%E6%95%B0%E6%8D%AE%E5%BA%93%E6%81%A2%E5%A4%8D%E6%8A%80%E6%9C%AF/" rel="next" title="数据库原理：数据库恢复技术">
                  数据库原理：数据库恢复技术 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">鸣蜩十七</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  




  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
